package com.wm.blog_web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wm.blog_common.base.BeanUtils;
import com.wm.blog_common.bean.PageHelper;
import com.wm.blog_common.bean.QueryPage;
import com.wm.blog_common.domain.TTagDO;
import com.wm.blog_common.entity.TBlog;
import com.wm.blog_common.entity.TFile;
import com.wm.blog_common.entity.TTag;
import com.wm.blog_common.enums.DeleteFlag;
import com.wm.blog_common.enums.PublishFlag;
import com.wm.blog_common.result.Result;
import com.wm.blog_web.controller.resp.TagResp;
import com.wm.blog_web.dao.TBlogDAO;
import com.wm.blog_web.dao.TTagDAO;
import com.wm.blog_web.query.TTagQuery;
import com.wm.picture_interface.feign.PictureFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * <p>
 * 标签表 服务实现类
 * </p>
 *
 * @author 半卷流年
 * @since 2020-03-24
 */
@Service
@Slf4j
public class TTagService {
    @Autowired
    private TTagDAO tTagDAO;

    @Autowired
    private PictureFeignClient pictureFeignClient;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private TBlogDAO tBlogDAO;

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    public Result<TTagDO> selectById(Long id) {
        return Result.success(BeanUtils.copyProperties(tTagDAO.getById(id), TTagDO.class));
    }

    /**
     * 根据ID删除
     *
     * @param id
     * @return
     */
    public Result deleteById(Long id) {
        return tTagDAO.removeById(id) ? Result.success() : Result.failure();
    }

    /**
     * 添加
     *
     * @param tTag
     * @return
     */
    public Result insert(TTag tTag) {
        return tTagDAO.save(tTag) ? Result.success() : Result.failure();
    }

    /**
     * 修改
     *
     * @param tTag
     * @return
     */
    public Result update(TTag tTag) {
        return tTagDAO.updateById(tTag) ? Result.success() : Result.failure();
    }

    /**
     * 统计总数
     *
     * @param query
     * @return
     */
    public Result<Integer> count(TTagQuery query) {
        return Result.success(tTagDAO.count(this.combineQuery(query)));
    }

    /**
     * 列表查询
     *
     * @param query
     * @return
     */
    public Result<List<TTagDO>> list(TTagQuery query) {
        return Result.success(BeanUtils.copyListProperties(tTagDAO.list(this.combineQuery(query)), TTagDO.class));
    }

    /**
     * 分页查询
     *
     * @param page
     * @return
     */
    public Result<Page<TTagDO>> page(QueryPage page, TTagQuery query) {
        return Result.success(PageHelper.newPage(tTagDAO.page(page, this.combineQuery(query)), TTagDO.class));
    }

    /**
     * 组装查询条件
     *
     * @param query
     * @return
     */
    private QueryWrapper<TTag> combineQuery(TTagQuery query) {
        QueryWrapper<TTag> wrapper = new QueryWrapper<>();
        Optional.ofNullable(query).ifPresent(item -> {
            Optional.ofNullable(query.getStatus()).ifPresent(x -> {
                wrapper.eq("status", x);
            });
        });
        return wrapper;
    }


    /**
     * 查询未被禁用的集合
     *
     * @return
     */
    public Result tagList() {
        TTagQuery query = new TTagQuery();
        query.setStatus(DeleteFlag.ENABLE.getValue());
        QueryWrapper<TTag> wrapper = this.combineQuery(query);
        List<TTag> tTags = Optional.ofNullable(tTagDAO.list(wrapper)).orElse(Collections.emptyList());
        List<TagResp> respList = Optional.ofNullable(BeanUtils.copyListProperties(tTags, TagResp.class)).orElse(Collections.emptyList());
        if (!CollectionUtils.isEmpty(tTags)) {
            List<Long> picIdList = respList.stream().map(TagResp::getFileId).distinct().collect(Collectors.toList());
            CompletableFuture<Map<Long, String>> futurePic = CompletableFuture.supplyAsync(() -> {
                return Optional
                        .ofNullable(pictureFeignClient.getByIdList(picIdList).getData())
                        .orElse(Collections.emptyList())
                        .stream()
                        .collect(Collectors.toMap(TFile::getId, TFile::getPicUrl));
            }, threadPoolTaskExecutor);
            //统计标签的文章数量,
            CompletableFuture<Void> futureCount = CompletableFuture.runAsync(() -> {
                respList.forEach(item -> {
                    QueryWrapper<TBlog> queryWrapper = new QueryWrapper<>();
                    queryWrapper.apply(String.format("find_in_set(%s,tag_id)",item.getId()));
                    queryWrapper.eq("is_publish", PublishFlag.PUBLISH.getValue());
                    queryWrapper.eq("status",DeleteFlag.ENABLE.getValue());
                    int count = tBlogDAO.count(queryWrapper);
                    item.setArticleCount(count);
                });
            }, threadPoolTaskExecutor);
            try {
                Map<Long, String> map = futurePic.get();
                futureCount.get();
                respList.forEach(item -> {
                    item.setPicUrl(map.getOrDefault(item.getFileId(),null));
                });
                return Result.success(respList);
            } catch (InterruptedException | ExecutionException e) {
               log.error("线程执行异常:{}",e.getMessage(),e);
            }
        }
        return Result.success();
    }
}







